#include <stdio.h>
#include <stdint.h>
#include <fcntl.h>  // 添加这一行来包含 fcntl.h
#include <unistd.h>
#include <stdint.h>
// 禁止内存对齐
#pragma pack(1)
struct partition_entry {
    uint8_t boot_flag;           // 引导标志
    uint8_t start_head;          // 起始磁道号
    uint8_t start_sector;        // 起始扇区号
    uint8_t start_cylinder;      // 起始柱面号
    uint8_t partition_type;      // 分区类型
    uint8_t end_head;            // 结束磁道号
    uint8_t end_sector;          // 结束扇区号
    uint8_t end_cylinder;        // 结束柱面号
    uint32_t start_lba;          // 本分区之前已经占用的扇区数
    uint32_t size_lba;           // 本分区的总扇区数
};
#pragma pack()

// 打印分区信息
void print_partition_info(struct partition_entry *entry, int index) {
    printf("Partition %d:\n", index + 1);
    printf("  Bootable: %s\n", entry->boot_flag == 0x80 ? "Yes" : "No");
    printf("  Partition type: 0x%02x\n", entry->partition_type);
    printf("  Start Head: %u\n", entry->start_head);
    printf("  Start Sector: %u\n", entry->start_sector);
    printf("  Start Cylinder: %u\n", entry->start_cylinder);
    printf("  End Head: %u\n", entry->end_head);
    printf("  End Sector: %u\n", entry->end_sector);
    printf("  End Cylinder: %u\n", entry->end_cylinder);
    printf("  Start LBA: %u\n", entry->start_lba);
    printf("  Size LBA: %u\n", entry->size_lba);
}

int main() {
    uint8_t mbr[512];  // 用来存储MBR数据
    int fd = open("/dev/vda", O_RDONLY);  // 根据需要修改设备路径
    if (fd == -1) {
        perror("Failed to open disk");
        return 1;
    }

    // 读取512字节MBR
    ssize_t bytes_read = read(fd, mbr, sizeof(mbr));
    if (bytes_read != 512) {
        perror("Failed to read MBR");
        close(fd);
        return 1;
    }

    // 检查MBR签名
    if (mbr[510] != 0x55 || mbr[511] != 0xAA) {
        printf("Invalid MBR signature: 0x%02X 0x%02X\n", mbr[510], mbr[511]);
        close(fd);
        return 1;
    }

    printf("MBR signature is valid: 0x55 0xAA\n");
    for(int i=0;i<512;i++){
      printf("%u  ",mbr[i]);
      if(i%32==0)printf("\n");
      if(i==446)printf("flag");
    }
    // 解析每个分区的内容
    for (int i = 0; i < 4; i++) {
        struct partition_entry *entry = (struct partition_entry *)(mbr + 446 + i * 16);
        print_partition_info(entry, i);
    }
    

    close(fd);
    return 0;
}

